package com.tbgov.util;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.mock.web.MockMultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;

public class Base64ToMultipartFileUtil {

    /**
     * 将 Base64 字符串转换为 MultipartFile
     *
     * @param base64    Base64 编码的字符串
     * @return MultipartFile
     * @throws IOException 如果解析失败
     */
    public static MultipartFile base64ToMultipartFile(String base64) throws IOException {
        // 检查并提取 Base64 前缀（如有）
        String[] base64Parts = base64.split(",");
        String mimeType = null;
        if (base64Parts.length > 1 && base64Parts[0].contains("data:")) {
            mimeType = base64Parts[0].substring(5, base64Parts[0].indexOf(";"));
        }
        String base64Content = base64Parts.length > 1 ? base64Parts[1] : base64Parts[0];

        // 解码 Base64 数据
        byte[] decodedBytes = Base64.getDecoder().decode(base64Content);

        // 根据 MIME 类型生成文件名
        String fileExtension = BaseUtil.getFileExtensionFromMimeType(mimeType);
        String fileName = "uploaded-file." + fileExtension;

        // 构造 MultipartFile
        return new MockMultipartFile(fileName, fileName, mimeType, new ByteArrayInputStream(decodedBytes));
    }
}
